package com.ydkfjs.handler.exception;

import com.ydkfjs.common.Result;
import com.ydkfjs.constants.HttpStatus;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * valid验证异常处理器
 * @Author: hb
 * @CreateTime: 2023-12-25 06:20
 * @Version: 1.0
 */
@Slf4j
@RestControllerAdvice
public class ValidExceptionHandler {

    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<?> handleMethodArgumentNotValid(MethodArgumentNotValidException e) {
        log.error("methodArgumentNotValidException", e);
        String message = "参数异常";
        BindingResult bindingResult = e.getBindingResult();
        if (bindingResult.hasErrors()) {
            List<ObjectError> allErrors = bindingResult.getAllErrors();
            if (!allErrors.isEmpty()) {
                FieldError fieldError = (FieldError) allErrors.get(0);
                message = fieldError.getDefaultMessage();
            }
        }
        return Result.fail(HttpStatus.ERROR, message);
    }
}
